from django.shortcuts import render, redirect, get_object_or_404
from django.contrib.auth.decorators import login_required
from django.db import connection, transaction
from django.http import JsonResponse, HttpResponseRedirect
from django.contrib import messages
from django.utils import timezone
from django.urls import reverse

# 辅助函数：将查询结果转换为字典
def dictfetchall(cursor):
    """将游标返回的结果转换为字典"""
    columns = [col[0] for col in cursor.description]
    return [
        dict(zip(columns, row))
        for row in cursor.fetchall()
    ]

@login_required
def cart_view(request):
    """用户购物车视图"""
    user_id = request.user.user_id
    
    # 获取用户购物车商品
    with connection.cursor() as cursor:
        # 获取购物车商品
        cursor.execute("""
            SELECT cart_id, box_id, quantity, selected, 
                   create_time, update_time
            FROM tb_cart
            WHERE user_id = %s
            ORDER BY update_time DESC
        """, [user_id])
        
        user_cart_items = dictfetchall(cursor)
        
        # 如果用户购物车为空，直接返回空列表
        if not user_cart_items:
            context = {
                'title': '我的购物车',
                'cart_items': [],
                'total_price': 0,
                'total_quantity': 0
            }
            return render(request, 'shopping/cart.html', context)
        
        # 获取对应的盲盒信息
        box_ids = [item['box_id'] for item in user_cart_items]
        
        placeholders = ', '.join(['%s'] * len(box_ids))
        cursor.execute(f"""
            SELECT box_id, name, image_url, discount_price, original_price, stock
            FROM tb_blind_box
            WHERE box_id IN ({placeholders})
        """, box_ids)
        
        box_info = {box['box_id']: box for box in dictfetchall(cursor)}
        
        # 组合购物车项目
        cart_items = []
        total_price = 0
        total_quantity = 0
        
        for item in user_cart_items:
            box_id = item['box_id']
            if box_id in box_info:
                cart_item = {
                    'cart_item_id': item['cart_id'],  # 使用cart_id作为cart_item_id
                    'box_id': box_id,
                    'quantity': item['quantity'],
                    'selected': item['selected'],
                    'name': box_info[box_id]['name'],
                    'image_url': box_info[box_id]['image_url'],
                    'discount_price': box_info[box_id]['discount_price'],
                    'original_price': box_info[box_id]['original_price'],
                    'stock': box_info[box_id]['stock']
                }
                
                if item['selected']:
                    item_total = item['quantity'] * box_info[box_id]['discount_price']
                    cart_item['item_total'] = item_total
                    total_price += item_total
                    total_quantity += item['quantity']
                else:
                    cart_item['item_total'] = 0
                
                cart_items.append(cart_item)
    
    context = {
        'title': '我的购物车',
        'cart_items': cart_items,
        'total_price': total_price,
        'total_quantity': total_quantity
    }
    
    return render(request, 'shopping/cart.html', context)

@login_required
def add_to_cart(request):
    """添加商品到购物车"""
    if request.method != 'POST':
        return redirect('blindbox:list')
    
    box_id = request.POST.get('box_id')
    quantity = int(request.POST.get('quantity', 1))
    user_id = request.user.user_id
    
    if not box_id:
        messages.error(request, '参数错误')
        return HttpResponseRedirect(request.META.get('HTTP_REFERER', '/'))
    
    try:
        with connection.cursor() as cursor:
            # 检查盲盒是否存在且有库存
            cursor.execute("""
                SELECT box_id, stock FROM tb_blind_box 
                WHERE box_id = %s AND status = 1
            """, [box_id])
            box_result = cursor.fetchone()
            
            if not box_result:
                messages.error(request, '商品不存在或已下架')
                return HttpResponseRedirect(request.META.get('HTTP_REFERER', '/'))
            
            if box_result[1] < quantity:
                messages.error(request, '商品库存不足')
                return HttpResponseRedirect(request.META.get('HTTP_REFERER', '/'))
            
            # 检查商品是否已在购物车中
            cursor.execute("""
                SELECT cart_id, quantity FROM tb_cart
                WHERE user_id = %s AND box_id = %s
            """, [user_id, box_id])
            item_result = cursor.fetchone()
            
            now = timezone.now()
            if item_result:
                # 更新购物车商品数量
                new_quantity = item_result[1] + quantity
                cursor.execute("""
                    UPDATE tb_cart
                    SET quantity = %s, update_time = %s
                    WHERE cart_id = %s
                """, [new_quantity, now, item_result[0]])
                messages.success(request, '已更新购物车中的商品数量')
            else:
                # 添加新商品到购物车
                cursor.execute("""
                    INSERT INTO tb_cart (user_id, box_id, quantity, selected, create_time, update_time)
                    VALUES (%s, %s, %s, %s, %s, %s)
                """, [user_id, box_id, quantity, True, now, now])
                messages.success(request, '商品已添加到购物车')
            
        return HttpResponseRedirect(request.META.get('HTTP_REFERER', '/'))
    
    except Exception as e:
        messages.error(request, f'添加到购物车失败：{str(e)}')
        return HttpResponseRedirect(request.META.get('HTTP_REFERER', '/'))

@login_required
def update_cart(request):
    """更新购物车商品数量和选中状态"""
    if request.method != 'POST':
        return JsonResponse({'status': 'error', 'message': '请求方法错误'})
    
    try:
        item_id = request.POST.get('item_id')
        action = request.POST.get('action')
        user_id = request.user.user_id
        
        with connection.cursor() as cursor:
            # 验证商品是否在用户的购物车中
            cursor.execute("""
                SELECT c.cart_id, c.quantity, bb.stock, c.selected, c.box_id
                FROM tb_cart c
                JOIN tb_blind_box bb ON c.box_id = bb.box_id
                WHERE c.cart_id = %s AND c.user_id = %s
            """, [item_id, user_id])
            
            item = cursor.fetchone()
            if not item:
                return JsonResponse({'status': 'error', 'message': '商品不存在或不在您的购物车中'})
            
            now = timezone.now()
            
            if action == 'increase':
                # 增加数量
                if item[1] >= item[2]:  # 如果当前数量已达到库存上限
                    return JsonResponse({'status': 'error', 'message': '已达到库存上限'})
                
                new_quantity = item[1] + 1
                cursor.execute("""
                    UPDATE tb_cart
                    SET quantity = %s, update_time = %s
                    WHERE cart_id = %s
                """, [new_quantity, now, item_id])
                
                return JsonResponse({
                    'status': 'success',
                    'message': '数量已增加',
                    'new_quantity': new_quantity,
                    'item_total': new_quantity * float(item[2])
                })
                
            elif action == 'decrease':
                # 减少数量
                if item[1] <= 1:
                    return JsonResponse({'status': 'error', 'message': '数量已是最小值'})
                
                new_quantity = item[1] - 1
                cursor.execute("""
                    UPDATE tb_cart
                    SET quantity = %s, update_time = %s
                    WHERE cart_id = %s
                """, [new_quantity, now, item_id])
                
                return JsonResponse({
                    'status': 'success',
                    'message': '数量已减少',
                    'new_quantity': new_quantity,
                    'item_total': new_quantity * float(item[2])
                })
                
            elif action == 'toggle':
                # 切换选中状态
                new_selected = not item[3]
                cursor.execute("""
                    UPDATE tb_cart
                    SET selected = %s, update_time = %s
                    WHERE cart_id = %s
                """, [new_selected, now, item_id])
                
                return JsonResponse({
                    'status': 'success',
                    'message': '已更新选中状态',
                    'selected': new_selected
                })
            
            else:
                return JsonResponse({'status': 'error', 'message': '未知操作'})
    
    except Exception as e:
        return JsonResponse({'status': 'error', 'message': f'操作失败：{str(e)}'})

@login_required
def remove_from_cart(request, item_id):
    """从购物车中移除商品"""
    user_id = request.user.user_id
    
    try:
        with connection.cursor() as cursor:
            # 验证商品是否在用户的购物车中
            cursor.execute("""
                SELECT cart_id FROM tb_cart
                WHERE cart_id = %s AND user_id = %s
            """, [item_id, user_id])
            
            if not cursor.fetchone():
                messages.error(request, '商品不存在或不在您的购物车中')
                return redirect('shopping:cart')
            
            # 删除购物车项
            cursor.execute("""
                DELETE FROM tb_cart
                WHERE cart_id = %s
            """, [item_id])
            
            messages.success(request, '商品已从购物车中移除')
    
    except Exception as e:
        messages.error(request, f'移除失败：{str(e)}')
    
    return redirect('shopping:cart')

@login_required
def select_all(request):
    """全选/取消全选购物车商品"""
    if request.method != 'POST':
        return JsonResponse({'status': 'error', 'message': '请求方法错误'})
    
    try:
        select_all = request.POST.get('select_all') == 'true'
        user_id = request.user.user_id
        
        with connection.cursor() as cursor:
            # 更新用户购物车中所有商品的选中状态
            cursor.execute("""
                UPDATE tb_cart
                SET selected = %s, update_time = %s
                WHERE user_id = %s
            """, [select_all, timezone.now(), user_id])
            
            # 获取更新后的购物车详情
            cursor.execute("""
                SELECT c.cart_id, c.box_id, c.quantity, c.selected,
                       bb.name, bb.discount_price
                FROM tb_cart c
                JOIN tb_blind_box bb ON c.box_id = bb.box_id
                WHERE c.user_id = %s
            """, [user_id])
            
            items = dictfetchall(cursor)
            
            # 计算总价和总数量
            total_price = 0
            total_quantity = 0
            
            for item in items:
                if item['selected']:
                    item_total = item['quantity'] * item['discount_price']
                    total_price += item_total
                    total_quantity += item['quantity']
        
        return JsonResponse({
            'status': 'success',
            'message': '已更新全部商品选中状态',
            'total_price': total_price,
            'total_quantity': total_quantity
        })
        
    except Exception as e:
        return JsonResponse({'status': 'error', 'message': f'操作失败：{str(e)}'})

@login_required
def clear_cart(request):
    """清空购物车"""
    if request.method != 'POST':
        return JsonResponse({'status': 'error', 'message': '请求方法错误'})
    
    user_id = request.user.user_id
    
    try:
        with connection.cursor() as cursor:
            # 删除用户购物车中所有商品
            cursor.execute("""
                DELETE FROM tb_cart
                WHERE user_id = %s
            """, [user_id])
        
        messages.success(request, '购物车已清空')
        return JsonResponse({'status': 'success', 'message': '购物车已清空'})
        
    except Exception as e:
        return JsonResponse({'status': 'error', 'message': f'操作失败：{str(e)}'})

@login_required
def checkout(request):
    """结算购物车选中商品"""
    if request.method != 'POST':
        return redirect('shopping:cart')
    
    user_id = request.user.user_id
    
    try:
        with connection.cursor() as cursor:
            # 获取购物车选中的商品
            cursor.execute("""
                SELECT c.cart_id, c.box_id, c.quantity, bb.name, 
                       bb.discount_price, bb.stock
                FROM tb_cart c
                JOIN tb_blind_box bb ON c.box_id = bb.box_id
                WHERE c.user_id = %s AND c.selected = 1
            """, [user_id])
            
            selected_items = dictfetchall(cursor)
            
            if not selected_items:
                messages.error(request, '请先选择要结算的商品')
                return redirect('shopping:cart')
            
            # 检查库存
            for item in selected_items:
                if item['quantity'] > item['stock']:
                    messages.error(request, f'"{item["name"]}"库存不足，请修改购买数量')
                    return redirect('shopping:cart')
            
            # 计算总价
            total_price = sum(item['quantity'] * item['discount_price'] for item in selected_items)
            
            # 创建订单
            now = timezone.now()
            order_no = f"ORD{now.strftime('%Y%m%d%H%M%S')}{user_id}"
            
            cursor.execute("""
                INSERT INTO tb_order (order_no, user_id, total_amount, status, create_time, update_time)
                VALUES (%s, %s, %s, %s, %s, %s)
                RETURNING order_id
            """, [order_no, user_id, total_price, 1, now, now])  # 状态1表示待支付
            
            order_id = cursor.fetchone()[0]
            
            # 创建订单项
            order_items = []
            for item in selected_items:
                cursor.execute("""
                    INSERT INTO tb_order_item (order_id, box_id, quantity, price, create_time)
                    VALUES (%s, %s, %s, %s, %s)
                """, [order_id, item['box_id'], item['quantity'], item['discount_price'], now])
                
                # 更新库存
                cursor.execute("""
                    UPDATE tb_blind_box
                    SET stock = stock - %s
                    WHERE box_id = %s
                """, [item['quantity'], item['box_id']])
                
                order_items.append({
                    'box_id': item['box_id'],
                    'cart_id': item['cart_id']
                })
            
            # 删除已结算的购物车项
            for item in order_items:
                cursor.execute("""
                    DELETE FROM tb_cart
                    WHERE cart_id = %s
                """, [item['cart_id']])
            
            # 跳转到支付页面
            return redirect('order:pay', order_id=order_id)
            
    except Exception as e:
        messages.error(request, f'结算失败：{str(e)}')
        return redirect('shopping:cart') 